<?php
declare(strict_types=1);

namespace SixShop\WechatPay;

use SixShop\System\ExtensionManager;
use WeChatPay\Crypto\Rsa;

/**
 * 微信支付配置
 * @package SixShop\WechatPay
 * @property string $mchid 商户号
 * @property string $appid 应用ID
 * @property string $serial_no 商户证书序列号
 * @property string $public_key_id 微信支付公钥id
 * @property string $api_v3_key APIv3密钥
 * @property string $notify_url 微信支付回调地址
 * @property string $apiclient_cert 微信支付证书  用于服务端API请求报文签名
 * @property string $apiclient_key 微信支付证书密钥 用于生成接口请求签名
 * @property string $public_key 微信支付公钥
 * @property string $platform_no 平台证书序列号
 * @property string $platform_cert 平台证书
 * @property string $refund_notify_url 退款回调地址
 * @property bool $debug 调试模式
 *
 */
class Config
{


    public function __construct(
        private readonly ExtensionManager $extensionManager,
        private ?array                    $options = null
    )
    {
    }

    public function __get(string $name)
    {
        if ($this->options === null) {
            $this->options = $this->extensionManager->getExtensionConfig('wechatpay');
            if (empty($this->options)) {
                throw new \RuntimeException('微信支付配置不能为空');
            }
        }
        return match ($name) {
            'debug' => $this->options['debug'] ?? false,
            'apiclient_cert' => $this->getKeyPath($this->options['apiclient_cert'][0]),
            'apiclient_key' => Rsa::from($this->getKeyPath($this->options['apiclient_key'][0])),
            'public_key' => Rsa::from($this->getKeyPath($this->options['public_key'][0]), Rsa::KEY_TYPE_PUBLIC),
            'platform_cert' => isset($this->options['platform_cert'][0]) ? Rsa::from($this->getKeyPath($this->options['platform_cert'][0]), Rsa::KEY_TYPE_PUBLIC) : null,
            default => $this->options[$name] ?? null,
        };
    }

    public function getKeyPath(string $name): string
    {
        return 'file://' . public_path() . $name;
    }
}